package com.weds.edjk.common.mqtt;


import com.alibaba.fastjson.JSONObject;
import com.weds.edjk.service.UserMonitorService;
import com.weds.edjk.util.RestTemplateUtils;
import com.weds.edjk.vo.ReportMqttVo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @Author 张从阵
 * @Description mqtt回调实体
 * 考勤记录示例	20000036,2019-09-11 14:42:28,c,0,,,jk529486,205829671,23,AABBCCDD
 * 活体攻击示例	100000000, 2019-09-11 14:42:28,c,0,,,jk529486,liveattch,23,
 * 经纬度	228886,2020-03-05 11:03:18,c,0,1,1,jk397982,537141833,4,B539667E,,,,121.39229011666666,37.418793199999996
 * @Date 2020-6-20
 */
@Component
public class ReportMqtt implements MqttCallback {
    /**
     * mqtt主机名
     */
    @Value("${mqtt.url}")
    public   String HOST ;
    /**
     * 标题
     */
    @Value("${mqtt.receiver.defaultTopic}")
    public  String TOPIC;
    /**
     * 账号
     */
    @Value("${mqtt.username}")
    private  String name;
    /**
     * 密码
     */
    @Value("${mqtt.password}")
    private  String passWord ;
    /**
     * 上送地址
     */
    @Value("${mqtt.report.url}")
    private  String mqttReportUrl ;
    @Value("${weds.scm.root-path}")
    private String rootPath;

    @Value("${weds.scm.photo-path}")
    private String photoPath;

    @Value("${weds.scm.frame-path}")
    private String framePath;

    private MqttClient client;
    private MqttConnectOptions options;
    /**
     * 人员监控服务
     */
    @Resource
    private UserMonitorService userMonitorService;

    /**
     * clientId不能重复所以这里我设置为系统时间
     */
    String  clientid= String.valueOf(System.currentTimeMillis());

    private Logger log = LogManager.getLogger();

    /**
     * 连接mqtt
     */
    @PostConstruct
    public void result() {
        try {
            log.info("连接mqtt开始");
            // host为主机名，clientid即连接MQTT的客户端ID，一般以唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            client = new MqttClient(HOST, clientid, new MemoryPersistence());
            // MQTT的连接设置
            options = new MqttConnectOptions();
            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            // 设置连接的用户名
            options.setUserName(name);
            // 设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(3600);
            // 设置回调
            client.setCallback(this);
            client.connect(options);
            //订阅消息
            int[] Qos  = {1};
            String[] topic1 = {TOPIC};
            client.subscribe(topic1, Qos);
            log.info("连接mqtt完成");
        } catch (Exception e) {
            log.info("ReportMqtt客户端连接异常，异常信息："+e);
            System.out.println("ReportMqtt客户端连接异常，异常信息：");
        }

    }

    /**
     * 重新连接
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
        try {
            log.info("程序出现异常，DReportMqtt断线！正在重新连接...:");
            client.close();
            this.result();
            log.info("ReportMqtt重新连接成功");
        } catch (MqttException e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 回调  回调后同步上送展示参数
     * @param topic
     * @param message
     */
    @Override
    public void messageArrived(String topic, MqttMessage message)  {
        log.info("接收消息内容 :"+ new String(message.getPayload()));
        JSONObject jo = JSONObject.parseObject(new String(message.getPayload()));
        // 用户信息字符串 一次刷卡会返回多个包 取带参数的上送
        if(null != jo.get("inStr")){
            String inStr = String.valueOf(jo.get("inStr")) ;
            ReportMqttVo reportMqttVo = userMonitorService.getCurrentUser(inStr);
            JSONObject jsonObject = new JSONObject();
            System.out.println("上送："+jsonObject.toJSONString(reportMqttVo));
            ResponseEntity response = RestTemplateUtils.sendMqtt(mqttReportUrl, reportMqttVo);
            log.info("response:"+response.getBody());
        }
    }

    /**
     * 发送状态
     * @param iMqttDeliveryToken
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.info("消息发送成功");
        log.info("deliveryComplete---------" + iMqttDeliveryToken.isComplete());
    }
}